import React, { useState, useEffect, useCallback} from 'react';
import {
  Form,
  Table,
  Input,
  Button,
  Select,
  Space,
  Divider,
  Breadcrumb,
  message,
  Modal,
} from 'antd';
import { IAllProps } from '@/typings/types';
import { getStudentList, deleteStudentInfoByIds } from '@/services/basic/student';
import { IStudent, IStudentParams } from '@/typings/student';
import { ColumnProps } from 'antd/lib/table';
import CreateForm from './component/CreateForm';
import styles from './styles.less';

const Student = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<IStudent[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [refresh, setRefresh] = useState<boolean>(false);
  const [type, setType] = useState<string>('add');
  const [willEditStudent,setWillEditStudent]  = useState<IAllProps>({})

  const queryStudentList = useCallback(async (params?: IStudentParams) => {
    // const result = await getStudentList(params);
    const result = await getStudentList(params);
    // console.log(result);
    const { code, data } = result;
    if (code === 0) {
      setDataSource(data.rows);
    }
  }, []);

  useEffect(() => {
    let cancel = false;
    !cancel && queryStudentList();

    return () => {
      cancel = true;
    };
  }, [refresh]);

  const refreshList = useCallback(() => {
    setRefresh((refresh) => !refresh);
  }, []);

  const handleEdit = (record: IStudent) => {
    setWillEditStudent(record);
    setCreateModalVisible(true);
    setType('edit');
  };

  const handleDelete = async (record: IStudent) => {
    Modal.confirm({
      title: '提示',
      content: `确定要删除${record.studentName}吗?`,
      onOk: async () => {
        const result = await deleteStudentInfoByIds(record.id);
        const { code } = result;
        if (code === 0) {
          message.success('删除成功');
          setRefresh(!refresh);
        } else {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = (values: IAllProps) => {
    queryStudentList(values);
    console.log('Success:', values);
  };

  const columns: ColumnProps<IStudent>[] = [
    {
      title: '学生姓名',
      dataIndex: 'studentName',
    },
    {
      title: '院系编号',
      dataIndex: 'schoolFacultyId',
    },
    {
      title: '专业编号',
      dataIndex: 'schoolSpecialId',
    },
    {
      title: '班级名称',
      dataIndex: 'className',
    },
    {
      title: '年级',
      dataIndex: 'classGrade',
    },
    {
      title: '主修/辅修',
      dataIndex: 'studentPractice',
    },
    {
      title: '学籍状态',
      dataIndex: 'studentStatus',
    },
    {
      title: '状态',
      dataIndex: 'studentState',
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space>
          {/* {record.name} */}
          <a onClick={() => handleEdit(record)}>编辑 </a>
          <Divider type="vertical" />

          <a onClick={() => handleDelete(record)}>删除</a>
        </Space>
      ),
    },
  ];

  // const rowSelection = {
  //   onChange: (selectedRowKeys, selectedRows) => {
  //     console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  //   },
  //   getCheckboxProps: (record) => ({
  //     name: record.name,
  //   }),
  // };

  // 性能优化
  const handleHidden = useCallback(() => {
    setCreateModalVisible(false);
  }, []);

  const handleAddStudent = () => {
    setCreateModalVisible(true);
    setWillEditStudent({})
    setType('add');
  };

  return (
    <>
      <div>
        <Breadcrumb className={styles.top}>
          <Breadcrumb.Item>首页</Breadcrumb.Item>
          <Breadcrumb.Item>基础信息</Breadcrumb.Item>
          <Breadcrumb.Item>学生信息</Breadcrumb.Item>
        </Breadcrumb>
        <Form
          form={form}
          layout="inline"
          size="middle"
          className={styles.inquire}
          name="basic"
          initialValues={{
            school: '',
            profession: '',
            grade: '',
            class: '',
            degree: '',
            studentStatus: '',
            accountStatus: '',
          }}
          onFinish={handleSubmit}
        >
          <Form.Item label="院（系）" name="school">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="专业" name="profession">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="年级" name="grade">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="班级" name="class">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="学位" name="degree">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="学籍状态" name="studentStatus">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="账号状态" name="accountStatus">
            <Select>
              <Select.Option value="">全部</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="studentName">
            <Input placeholder="请输入学生姓名或学号" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
        <div className={styles.tableTop}>
          <h2>学生信息列表</h2>
          <div>
            <Button className={styles.Button1} onClick={handleAddStudent}>
              新增学生
            </Button>
            <Button className={styles.Button2}>批量导入</Button>
          </div>
        </div>
        <Table<IStudent>
          rowKey="id"
          columns={columns}
          dataSource={dataSource} 
        />
        <CreateForm
          type={type}
          willEditStudent={willEditStudent}
          modalVisible={createModalVisible}
          refreshList={refreshList}
          onCancel={handleHidden}
        />
      </div>
    </>
  );
};

export default React.memo(Student);
